package com.tl.khadmin.service.impl;
  
import java.io.File;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import com.tl.khadmin.bean.Order;
import com.tl.khadmin.bean.OrderAftersale;
import com.tl.khadmin.bean.OrderException;
import com.tl.khadmin.bean.OrderRefund;
import com.tl.khadmin.bean.Staff;
import com.tl.khadmin.bean.Supplier;
import com.tl.khadmin.mapper.OrderAftersaleMapper;
import com.tl.khadmin.mapper.OrderMapper;
import com.tl.khadmin.mapper.OrderProductMapper;
import com.tl.khadmin.mapper.OrderRefundMapper;
import com.tl.khadmin.page.Page;
import com.tl.khadmin.service.OrderAftersaleIService;
import com.tl.khadmin.util.CommonUtil;
import com.tl.khadmin.util.Constant;
import com.tl.khadmin.util.PutParamUtil; 

@Service
public class OrderAftersaleServiceImpl implements OrderAftersaleIService{
	
	@Resource
	private OrderAftersaleMapper orderAftersaleMapper;
	@Resource
	private OrderProductMapper orderProductMapper;
	@Resource
	private OrderRefundMapper orderRefundMapper; 
	@Resource
	private OrderMapper orderMapper;
	
	@Override
	public Map<String, Object> querybyId(Integer id) {
		OrderAftersale orderAftersale = orderAftersaleMapper.selectByPrimaryKey(id);
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("orderAftersale", orderAftersale);
		return result;
	}
	
	/**
	 * 保存售后信息
	 */
	@Override
	public String saveOrderAftersale(HttpSession session, OrderAftersale orderAftersale) { 
        try {
            Staff staff = (Staff) session.getAttribute(Constant.USER);
            orderAftersale.setCreateTime(new Date());
            orderAftersale.setStatus(1);
            orderAftersaleMapper.insertSelective(orderAftersale);
        } catch (Exception ex) {
            return CommonUtil.returnMapResultByRows(0, "提交成功", "提交失败，请重试");
        }
        return CommonUtil.returnMapResultByRows(1, "提交成功", "提交失败，请重试");
	}
	
	@Override
	public Map<String, Object> queryDetailById(Integer id) {
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("OrderAftersale", orderAftersaleMapper.queryDetailById(id)); 
		result.put("orderProductList", orderProductMapper.queryByOrderId(orderAftersaleMapper.selectByPrimaryKey(id).getOrderId()));
		return result;
	}
	
	public List<OrderAftersale> listOrderAftersale(Map<String, Object> param){
		return orderAftersaleMapper.listOrderAftersale(param); 
	}
	
	@Override
	public Page<OrderAftersale> showOrderAftersaleByPage(HttpSession session, Integer pageNum, 
			Integer pageSize, Map<String, Object> params) {
		Page<OrderAftersale> page=new Page<OrderAftersale>(pageNum, pageSize);
        params.put("page", page);   
        Supplier supplier = (Supplier) session.getAttribute(Constant.USER_SUPPLIER);
        PutParamUtil.setParamIsInterior(supplier, params);	//设置查询供应商数据范围 
        List<OrderAftersale> list= orderAftersaleMapper.showOrderAftersaleByPage(params);  
		page.setResult(list);
		return page;
	}
	
	/**
	 * 最终处理售后订单，录入最终价格
	 */
	@Override
	public String deal(HttpSession session, OrderAftersale orderAftersale) {
		OrderAftersale oa = new OrderAftersale();
		OrderAftersale old = orderAftersaleMapper.selectByPrimaryKey(orderAftersale.getId());
		oa.setId(orderAftersale.getId());
		oa.setFinalAmount(orderAftersale.getFinalAmount());
		oa.setStatus(3);
		oa.setSupplierAuditStatus(2);
		int result = orderAftersaleMapper.updateByPrimaryKeySelective(oa);
		//生成退款订单记录 
		OrderRefund orderRefund = new OrderRefund();
		orderRefund.setCause(old.getRemark());
		orderRefund.setCreateTime(new Date());
		orderRefund.setOrderId(old.getOrderId()); 
		orderRefund.setAmount(orderAftersale.getFinalAmount());
		int irow = orderRefundMapper.insertSelective(orderRefund);
		if(irow != 1) {
			return CommonUtil.returnMapResultToJson("fail", "保存失败");
		}
		return CommonUtil.returnMapResultByRows(result, "提交成功", "提交失败，请重试");
	}

	/**
	 * 客服审核售后订单
	 */
	@Override
	public String serviceAudit(HttpSession session, OrderAftersale orderAftersale) { 
		OrderAftersale oa = new OrderAftersale();
		Staff staff = (Staff) session.getAttribute(Constant.USER); 
		oa.setId(orderAftersale.getId());
		oa.setServiceAuditId(staff.getId());
		oa.setServiceAuditStatus(orderAftersale.getServiceAuditStatus());
		//客服审核状态，1待审核，2审核通过，3审核不通过
		if(orderAftersale.getServiceAuditStatus().intValue() == 2) {
			Order order = orderMapper.selectByPrimaryKey(orderAftersaleMapper.selectByPrimaryKey(orderAftersale.getId()).getOrderId());
			BigDecimal orderAmount = new BigDecimal(order.getOrderAmount());
			if(new BigDecimal(orderAftersale.getAmount()).compareTo(orderAmount) == 1) {
				return CommonUtil.returnMapResultToJson("fail", "退款金额不能大于订单金额");
			} 
			//审核通过才设置退款金额
			oa.setAmount(orderAftersale.getAmount());
		}
		oa.setServiceAuditTime(new Date());
		oa.setServiceAuditOpinion(orderAftersale.getServiceAuditOpinion()); 
		oa.setStatus(2);
		int result = orderAftersaleMapper.updateByPrimaryKeySelective(oa); 
		return CommonUtil.returnMapResultByRows(result, "提交成功", "提交失败，请重试"); 
	}
	
	/**
	 * 供应商处理售后订单
	 * 默认供应商提交退款金额与客户发起金额不一致代表供应商审核不通过，后线下沟通，由平台方确认最终退款金额，且生成退款订单
	 * 金额一致代表通过，且生成退款订单
	 */
	@Override
	public String supplierAudit(HttpSession session, OrderAftersale orderAftersale) {
		OrderAftersale oa = new OrderAftersale();
		Staff staff = (Staff) session.getAttribute(Constant.USER); 
		OrderAftersale old = orderAftersaleMapper.selectByPrimaryKey(orderAftersale.getId());
		oa.setId(orderAftersale.getId());
		oa.setSupplierAuditId(staff.getId());
		oa.setSupplierAuditOpinion(orderAftersale.getSupplierAuditOpinion());
		oa.setSupplierAuditTime(new Date());
		oa.setSupplierAuditAmount(orderAftersale.getSupplierAuditAmount());
		//退款金额与客户发起金额一致时
		if(orderAftersale.getSupplierAuditAmount().doubleValue() == old.getAmount().doubleValue()) {
			//供应商审核状态，1待审核，2审核通过，3审核不通过
			oa.setSupplierAuditStatus(2);
			
			//生成退款订单记录 
			OrderRefund orderRefund = new OrderRefund();
			orderRefund.setCause(old.getRemark());
			orderRefund.setCreateTime(new Date());
			orderRefund.setOrderId(old.getOrderId()); 
			orderRefund.setAmount(old.getAmount());
			int irow = orderRefundMapper.insertSelective(orderRefund);
			if(irow != 1) {
				return CommonUtil.returnMapResultToJson("fail", "保存失败");
			}
		}else{
			oa.setSupplierAuditStatus(3);
		}   
		int result = orderAftersaleMapper.updateByPrimaryKeySelective(oa);
		if(result != 1) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//事物回滚
		}
		return CommonUtil.returnMapResultByRows(result, "提交成功", "提交失败，请重试"); 
	}

	@Override
	public Map<String, String> upLoadAftersaleImg(String basePath, MultipartFile file) {
		Map<String, String> ret = new HashMap<String, String>();
        if (file == null) {
            ret.put("result", "fail");
            return ret;
        }
        try {
            DateFormat df = new SimpleDateFormat("yyyyMMddhhmmssSSS");
            File imgDir = new File(basePath);
            if (!imgDir.exists()) {
                imgDir.mkdirs();
            }
            String datePath = df.format(new Date());
            String picurl = datePath + ".jpg";
            File toFile = new File(basePath, picurl);
            file.transferTo(toFile);
            ret.put("result", "success");
            ret.put("message", "/upload/productimg/" + picurl);
            return ret;
        } catch (Exception e) {
            e.printStackTrace();
            ret.put("reulst", "fail");
            return ret;
        }
	}


}
